package metrics

import (
	"log"
	"net"
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
	"github.com/prometheus/client_golang/prometheus"
)

var MetricsCounter = prometheus.NewCounterVec(
	prometheus.CounterOpts{
		Name: "suber_example_counter",
		Help: "一个counter 类型的指标",
	},
	[]string{"method", "status", "sourceIP", "selfIP"}, // 定义 labels
)

func Counter(ctx *gin.Context) {
	addrs, _ := net.InterfaceAddrs()

	selfIP := ""
	for _, addr := range addrs {
		// 检查 IP 地址是否为回环地址
		if ipnet, ok := addr.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
			if ipnet.IP.To4() != nil { // 优先返回 IPv4
				selfIP = ipnet.IP.String()
			}
		}
	}
	// 创建Prometheus计数器指标，用于统计对/metrics端点的请求次数
	// 指标名称格式: <应用名>_<指标类型>_<描述>_total (遵循Prometheus命名最佳实践)
	log.Println("一个 conter 类型的指标, 统计请求 /counter 的次数")
	MetricsCounter.WithLabelValues(ctx.Request.Method, strconv.Itoa(http.StatusOK), ctx.Request.Host, selfIP).Inc()
	ctx.JSON(200, gin.H{
		"message": "successful",
	})
}
